<template>
  <v-app>
    <v-main>
      <v-container fill-height text-center align-center class="d-flex justify-center">
        <v-card class="elevation-16" min-width="400px">
          <div class="login-header">
            <img src="../assets/ETE-256-with-name-en.png" alt="guericke.cn" class="login-logo">
            <h1 class="login-title">欢迎使用灵犀系列网关</h1>
          </div>
          <v-card-text>
            <v-form>
              <v-text-field
                  label="邮箱"
                  placeholder="请输入邮箱账号"
                  required
                  prepend-icon="mdi-email"
                  v-model="email"
                  type="email"
                  @change="checkEmail()"
                  :error-messages="emailError ? [emailError] : []"
              ></v-text-field>
              <v-text-field
                  label="密码"
                  required
                  prepend-icon="mdi-lock"
                  v-model="password"
                  :type="showPassword ? 'text' : 'password'"
                  :append-icon="showPassword ? 'mdi-eye' : 'mdi-eye-off'"
                  :error-messages="pwdError ? [pwdError] : []"
                  @change="checkPassword"
                  @click:append="toggleShowPassword"
              ></v-text-field>
              <div class="d-flex justify-space-between align-center">
                <v-checkbox
                    v-model="keepLogin"
                    label="保持登录"
                    hide-details
                    dense
                ></v-checkbox>
                <v-tooltip bottom>
                  <template v-slot:activator="{ on }">
                      <span v-on="on" style="color: blue;">
                        <a @click.prevent @click="/*forgetPassword*/">忘记密码？</a>
                      </span>
                  </template>
                  <span>该功能暂未开放</span>
                </v-tooltip>

              </div>
              <div class="register">
                没有账号？去<a @click="goToRegister">注册</a>
              </div>
              <v-spacer></v-spacer>
              <v-btn color="primary" @click="login">登录</v-btn>
              <v-snackbar
                  v-model="snackbar.show"
                  :color="snackbar.color"
                  :timeout="1000"
                  multi-line
                  top
              >
                <template>
                  <v-icon v-if="snackbar.icon" :color="snackbar.iconColor">{{ snackbar.icon }}</v-icon>
                </template>
                {{ snackbar.text }}
                <v-spacer></v-spacer>
              </v-snackbar>
            </v-form>
          </v-card-text>
        </v-card>
      </v-container>
    </v-main>
  </v-app>
</template>
<script>
import axios from "axios";
import jwt_decode from 'jwt-decode';

export default {
  name: "Login-component",
  created() {
  },
  mounted() {
    const k = localStorage.getItem('keepLogin') === 'true';
    if (k) {
      this.$router.push('/home');
    }
  },
  data() {
    return {
      email: '',
      password: '',
      showPassword: false,
      keepLogin: false,
      emailError: '',
      pwdError: '',
      snackbar: {
        show: false,
        color: '',
        text: '',
        icon: '',
        iconColor: ''
      }
    };
  },
  methods: {
    checkEmail() {
      this.emailError = '';
      // 验证邮箱
      const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailPattern.test(this.email)) {
        this.emailError = '请输入有效的邮箱地址';
        return true;
      }
    },
    checkPassword() {
      this.pwdError = '';
      if (this.password === '') {
        this.pwdError = '请输入密码';
        return true;
      }
    },
    login() {
      // 在这里添加登录逻辑
      if (this.checkPassword() || this.checkEmail()) return;
      const loginData = {
        username: this.email,
        password: this.password
      }
      axios.post(`${this.$serverUrl}/api/auth/login`, loginData)
          .then(response => {
            const token = response.data.token;
            const refreshToken = response.data.refreshToken;
            const decodedToken = jwt_decode(token);
            // console.log(decodedToken)
            axios.get(`${this.$serverUrl}/api/user/${decodedToken.userId}`, {
              headers: {
                'X-Authorization': `Bearer ${token}`
              }
            })
                .then(response => {
                  // console.log(response)
                  if (response.data.authority === "TENANT_ADMIN") {
                    localStorage.setItem('token', token);
                    localStorage.setItem('refreshToken', refreshToken);
                    localStorage.setItem('room', response.data.email)
                    localStorage.setItem('userName', response.data.name);
                    if (this.keepLogin) localStorage.setItem('keepLogin', 'true');
                    this.setSnackBar(true, 'success', '登陆成功', 'mdi-check', 'green');
                    setTimeout(() => {
                      this.$router.push('/home');
                    }, 500)
                  } else if (response.data.authority === "SYS_ADMIN" || response.data.authority === "CUSTOMER_USER") {
                    this.setSnackBar(true, 'error', '请登录租户账号', 'mdi-close-circle', 'red');
                  }
                })
          })
          .catch(error => {
            // console.log(error);
            if (error.response) {
              if (error.response.status === 404) this.setSnackBar(true, 'error', '服务器已掉线', 'mdi-close-circle', 'red');
              else if (error.response.status === 401) this.setSnackBar(true, 'error', '账号或密码错误', 'mdi-close-circle', 'red');
            } else if (error.request) {
              if (error.code === 'ERR_NETWORK') {
                this.setSnackBar(true, 'error', '网络异常', 'mdi-close-circle', 'red');
              } else {
                this.setSnackBar(true, 'error', '请求已发送，无响应', 'mdi-close-circle', 'red');
              }
            } else {
              this.setSnackBar(true, 'error', '配置错误', 'mdi-close-circle', 'red');
            }
          })
    },
    toggleShowPassword() {
      this.showPassword = !this.showPassword
    },
    setSnackBar(show, color, text, icon, iconColor) {
      this.snackbar.show = show;
      this.snackbar.color = color;
      this.snackbar.text = text;
      this.snackbar.icon = icon;
      this.snackbar.iconColor = iconColor;
    },
    forgetPassword() {
      this.$router.push('/forgetPassword');
    },
    goToRegister() {
      this.$router.push('/register');
    },
  },
};
</script>

<style scoped>
.login-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  padding-top: 4vh;
  padding-bottom: 4vh;
  background-color: #1976d2;
  color: white;
}

.login-logo {
  width: 60px; /* 或者你想要的任何尺寸 */
  height: auto;
  margin-right: 3vh;
  margin-top: 5px;
}

.login-title {
  font-size: 24px; /* 或者你想要的任何字体大小 */
}

.register {
  margin-bottom: 8px;
}
</style>
